package jhavelogger.client;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Properties;

/**
 * Connects to a JHaveLogger server. Sends all text from standard input
 * to the JHaveLogger server. The settings for this program are stored in
 * the logclient.properties file (stored in the top-level of this project).
 * 
 * Relevant properties:
 * server: hostname or IP address of the JHaveLogger server.
 * port: port number that the JHaveLogger server is running on
 * 
 * @author Jared Schlicht
 */
public class LogClient {
    /**
     * Begins the program
     * @param args command line arguments are ignored
     */
    public static void main(String[] args) {
	Socket socket = null;
	BufferedReader socketReceiver = null;
	PrintWriter socketSender = null;
	BufferedReader input = null;
	
	Properties clientProperties = new Properties();
	FileInputStream propertiesInput = null;
	
	String server = null;
	int port = -1;
	
	try {
	    
	    propertiesInput = new FileInputStream("logclient.properties");
	    clientProperties.load(propertiesInput);
	    server = clientProperties.getProperty("server");
	    port = Integer.parseInt(clientProperties.getProperty("port")); 
	} catch (Exception ex) {
	    ex.printStackTrace();
	    return;
	} finally {
	    if (propertiesInput != null) {
		try {
		    propertiesInput.close();
		} catch (IOException e) {
		    e.printStackTrace();
		}
	    }
	}
	
	System.out.println("Connecting to server: " + server + ":" + port);
	try {
	    socket = new Socket(server, port);
	    socketReceiver = new BufferedReader(new InputStreamReader(socket.getInputStream()));
	    socketSender = new PrintWriter(socket.getOutputStream(),true);
	    input = new BufferedReader(new InputStreamReader(System.in));
	    
	    String line;
	    System.out.println("Connected, now reading data:");
	    while ((line = input.readLine()) != null) {
		socketSender.println(line);
		System.out.println("Sent: " + line);
	    }
	} catch(Exception e) {
	    e.printStackTrace();
	} finally {
	    if (socketReceiver != null) {
		try {
		    socketReceiver.close();
		} catch (IOException e) {
		    e.printStackTrace();
		}
	    }
	    
	    if (socketSender != null) {
		socketSender.close();
	    }
	    
	    if (socket != null) {
		try {
		    socket.close();
		} catch (IOException e) {
		    e.printStackTrace();
		}
	    }
	    
	    if (input != null) {
		try {
		    input.close();
		} catch (IOException e) {
		    e.printStackTrace();
		}		
	    }
	}
    }
}
